<template>
  <el-dropdown @command="handleLanguageChange" trigger="click">
    <el-button class="language-switcher" type="text">
      <el-icon><Globe /></el-icon>
      {{ currentLanguage.name }}
      <el-icon><ArrowDown /></el-icon>
    </el-button>
    <template #dropdown>
      <el-dropdown-menu>
        <el-dropdown-item
          v-for="locale in availableLocales"
          :key="locale.code"
          :command="locale.code"
          :class="{ 'is-active': locale.code === currentLocale }"
        >
          {{ locale.name }}
        </el-dropdown-item>
      </el-dropdown-menu>
    </template>
  </el-dropdown>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Globe, ArrowDown } from '@element-plus/icons-vue'
import { useI18n } from 'vue-i18n'
import { availableLocales, setLocale } from '@/locales'

const { locale } = useI18n()

const currentLocale = computed(() => locale.value)

const currentLanguage = computed(() => {
  return availableLocales.find(lang => lang.code === currentLocale.value) || availableLocales[0]
})

const handleLanguageChange = (langCode: string) => {
  setLocale(langCode)
  ElMessage.success(`语言已切换为 ${currentLanguage.value.name}`)
}
</script>

<style scoped>
.language-switcher {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 8px 12px;
  border-radius: 4px;
  transition: background-color 0.3s ease;
}

.language-switcher:hover {
  background-color: var(--el-color-primary-light-9);
}

.is-active {
  color: var(--el-color-primary);
  font-weight: 500;
}
</style>